package com.tgy.leetcode;

import java.util.Stack;

/**
 * @Author: tgy
 * @Date: 2020-11-04 11:55
 *
 * https://leetcode-cn.com/problems/trapping-rain-water/
 */
public class _42_接雨水_双指针_03 {

    public int trap(int[] height) {

        if (height == null || height.length <= 2) {

            return 0;
        }

        int left = 0, right = height.length - 1;
        int index;
        int sumWater = 0;

        while (left < right) {

            if (height[left] <= height[right]) {
                // 如果左边小于等于右边，则从左边加一开始计算
                index = left+1;
                while (height[left] > height[index] && index < right) {

                    sumWater +=(height[left] - height[index]);
                    index++;
                }

                left = index;
            }else {

                index = right - 1;
                while (height[right] > height[index] && index > left) {

                    sumWater += (height[right] - height[index]);
                    index--;
                }

                right = index;
            }
        }

        return sumWater;
    }
}
